//
//  GCDTimer.m
//  MyFunctionDemo
//
//  Created by Ting Han on 2017/8/28.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "GCDTimer.h"
#import "GCDQueue.h"

@interface GCDTimer()

@property (nonatomic,strong) dispatch_queue_t dispatchQueue;
@property (nonatomic, copy) dispatch_block_t block;
@property (nonatomic, assign) NSTimeInterval interval;
@end

@implementation GCDTimer

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dispatchQueue = [GCDQueue globalQueue].dispatchQueue;
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, [GCDQueue globalQueue].dispatchQueue);
    }
    return self;
}
- (instancetype)initWithQueue:(GCDQueue *)queue{
    self = [super init];
    if (self) {
        self.dispatchQueue = queue.dispatchQueue;
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue.dispatchQueue);
    }
    return self;
}

- (void)execute: (dispatch_block_t)block interval: (NSTimeInterval)interval
{
    [self execute: block interval: interval delay: 0];
}

- (void)execute: (dispatch_block_t)block interval: (NSTimeInterval)interval delay: (NSTimeInterval)delay
{
    NSParameterAssert(block);
    self.block = block;
    self.interval = interval;
    dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.timer, block);
}

- (void)dealloc{
    [self stop];
}

- (void)resume{
    if (!_timer) {
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _dispatchQueue);
       
    }
    dispatch_resume(_timer);
}
- (void)stop{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }

}
-(void)suspend{
    if(_timer){
        dispatch_suspend(_timer);
    }
}

@end
